from django.shortcuts import render,HttpResponse
from myadmin.models import *  #导入后台中的会员模型
from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse
import json

#购物车
def cart(request):
    #获取当前用户的购物车数据
    VipUser=request.session.get('VipUser')
    data=Cart.objects.filter(uid=VipUser['uid'])
    #data.dumps(data)
    return render(request,'myhome/cart.html',{'cartdata':data})

#加入购物车
def cart_add(request):
    #执行购物添加
    try:
        data=request.GET.dict()
        print(data)
        #把商品id 给购物车
        data['goodsid']=Goods.objects.get(id=data['goodsid'])
        #把用户id给购物车
        data['uid']=Users.objects.get(id=request.session.get('VipUser')['uid'])

        #检测商品是否在购物车中
        ob=Cart.objects.filter(uid=data['uid'],goodsid=data['goodsid'])
        if ob.count():
            #如果存在则把原有之数值取出来和现在的相加
            cart=Cart.objects.get(id=ob[0].id)
            cart.num+=int(data['num'])
            cart.save()
        else:
            ob=Cart(**data)
            ob.save()
        return JsonResponse({'code': 0, 'msg': '加入购物车成功'})
    except:
        pass
    return JsonResponse({'code': 1, 'msg': '加入购物车失败'})

#购物车ajax 数据更新
def cart_update(request):
    cart=request.GET.get('cart')
    num=request.GET.get('num')
    ob=Cart.objects.get(id=cart)
    ob.num=num
    ob.save()
    return JsonResponse({'msg':'修改成功'})

#删除购物车中的内容
def cart_del(request):
    cartid=request.GET.get('cart')
    ob=Cart.objects.get(id=cartid)
    ob.delete()
    return JsonResponse({'msg':'删除成功'})

#清空购物车
def cart_clear(request):

    cartid=request.GET.get('cart')
    print(cartid)
    uid=request.session.get('VipUser')['uid']
    #获取该用户下的所有购物车信息
    ob=Cart.objects.filter(uid=uid)
    ob.delete()
    return JsonResponse({'msg':'删除成功'})